<html>

<head>
  <title>String to AudioBuffer</title>
</head>

<body>
  <form>
    <input type="text" id="text" value="Hello, world!">
    <button type="button" onclick="convert()">Convert</button>
  </form>
</body>
<script>
  // www.javascriptcn.com code example
  function stringToUtf8ArrayBuffer(str) {
    const utf8 = unescape(encodeURIComponent(str));
    const buffer = new ArrayBuffer(utf8.length);
    const view = new Uint8Array(buffer);
    for (let i = 0; i < utf8.length; i++) {
      view[i] = utf8.charCodeAt(i);
    }
    return buffer;
  }

  // www.javascriptcn.com code example
  function utf8ArrayBufferToString(buffer) {
    const view = new Uint8Array(buffer);
    let str = '';
    let i = 0;
    while (i < view.length) {
      const code = view[i];
      if (code < 128) {
        str += String.fromCharCode(code);
        i++;
      } else if (code >= 192 && code < 224) {
        str += String.fromCharCode((code & 0x1f) << 6 | (view[i + 1] & 0x3f));
        i += 2;
      } else if (code >= 224 && code < 240) {
        str += String.fromCharCode((code & 0x0f) << 12 | (view[i + 1] & 0x3f) << 6 | (view[i + 2] & 0x3f));
        i += 3;
      } else {
        str += String.fromCharCode((code & 0x07) << 18 | (view[i + 1] & 0x3f) << 12 | (view[i + 2] & 0x3f) << 6 | (view[i + 3] & 0x3f));
        i += 4;
      }
    }
    return decodeURIComponent(escape(str));
  }

  function convert() {
    const text = document.getElementById('text').value;
    const buffer = stringToUtf8ArrayBuffer(text);
    console.log(buffer);
  }
</script>

</html>